package cn.xeblog.plugin.ui;

import cn.xeblog.plugin.game.dld.Const;
import cn.xeblog.plugin.tools.AbstractPanelComponent;
import cn.xeblog.plugin.util.NotifyUtils;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import lombok.Data;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;

/**
 * @author eleven
 * @date 2023/12/14 14:39
 * @apiNote
 */
public class ImageUI extends AbstractPanelComponent {


    public static final String FOLDER = "BackgroundImagesFolder";
    public static final String AUTO_CHANGE = "BackgroundImagesAutoChange";
    public static final String INTERVAL = "BackgroundImagesInterval";

    private JPanel mainPanel;

    private BackgroundImageUI backgroundImageUI;

    public ImageUI(boolean initialized) {
        super(initialized);
    }

    @Override
    protected void init() {
        if (mainPanel == null) {
            backgroundImageUI = new BackgroundImageUI();
            mainPanel = backgroundImageUI.getMainPanel();
        }
        PropertiesComponent instance = PropertiesComponent.getInstance();
        TextFieldWithBrowseButton imageFolder = backgroundImageUI.getFolder();
        imageFolder.setText(instance.getValue(FOLDER));
        JCheckBox checkBox = backgroundImageUI.getCheckBox();
        checkBox.setSelected(instance.getBoolean(AUTO_CHANGE, false));
        JSpinner spinner = backgroundImageUI.getSpinner();
        spinner.setValue(instance.getInt(INTERVAL, 5));
        FileChooserDescriptor descriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor();
        imageFolder.addBrowseFolderListener(new TextBrowseFolderListener(descriptor) {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                String current = imageFolder.getText();
                if (!current.isEmpty()) {
                    fc.setCurrentDirectory(new File(current));
                }
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                fc.showOpenDialog(mainPanel);

                File file = fc.getSelectedFile();
                String path = file == null
                        ? ""
                        : file.getAbsolutePath();
                imageFolder.setText(path);
                instance.setValue(FOLDER, path);
            }
        });
        checkBox.addChangeListener(e -> {
            instance.setValue(AUTO_CHANGE, checkBox.isSelected());
        });
        spinner.addChangeListener( e -> {
            instance.setValue(INTERVAL, Integer.parseInt(spinner.getValue().toString()), 5);
        });
    }

    @Override
    protected JComponent getComponent() {
        return mainPanel;
    }
}
